package client.view;

import java.awt.event.ActionEvent;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JTextField;

import client.AccountProxy;
import client.LobbyClient;

public class PrivateChatFrame 
{
	private JFrame frame;
	private JTextField name;
	private ChatPane chat;
	private LobbyClient client;
	private CloseableTabbedPane ctp;
	
	public PrivateChatFrame(LobbyClient client) {
		this.client = client;
		createInterface();
		frame.setVisible(false);
	}
	public void readMessage(String msg) {
		System.out.println("reading private message " + msg);
		String from = msg.split(":")[0];
		showTab(new AccountProxy(from));
		((ChatPane)(ctp.getSelectedComponent())).appendMessage(msg);
	}
	public void showTab(final AccountProxy ap) {
		if (ctp.indexOfTab(ap.getUserName())<0) {
			chat = new ChatPane(new AbstractAction(){
				public void actionPerformed(ActionEvent arg0) {
					try{
						client.sendMessage(ap.getUserName(), chat.getMessage());
						chat.appendMessage("Me: " + chat.getMessage());
					} catch(IOException e){
						e.printStackTrace();
					}
					
					chat.clearMessage();
				}
			});
			chat.setSize(300,400);
			
			ctp.addTab(ap.getUserName(),chat);
		}
		ctp.setSelectedIndex(ctp.indexOfTab(ap.getUserName()));
		frame.setVisible(true);
	}
	
	private void createInterface() {
		frame = new JFrame("Private Chat");
		frame.setSize(400, 400);
		
		ctp=new CloseableTabbedPane();
		frame.add(ctp);

		/*name = new JTextField();
		name.setSize(150,20);
		name.setLocation(100, 0);
		name.setText("Enter Name Here");
		frame.setLayout(new BorderLayout());
		chat = new ChatPane(new AbstractAction(){
			public void actionPerformed(ActionEvent arg0) {
				try{
					client.sendMessage(name.getText(), chat.getMessage());
				} catch(IOException e){
					e.printStackTrace();
				}
				
				chat.clearMessage();
			}
		});
		chat.setSize(300,400);
		frame.add(name);
		frame.add(chat);
		*/
		
		frame.setVisible(true);
	}
}

